#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using func_t = std::function<const std::string (const std::string &word)>;
#define DEFAULT_PORT 8888
#define DEFAULT_SOCKFD -1
#define SIZE 1024
class UdpServer
{
public:
    UdpServer(func_t func, uint16_t port = DEFAULT_PORT) 
        :_port(port), _sockfd(DEFAULT_SOCKFD), _func(func)
    {}
    void Init()
    {
        //1. 创建socket套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        //2.bind
        struct sockaddr_in myaddr;
        memset(&myaddr, 0, sizeof(myaddr));
        myaddr.sin_family = AF_INET;
        myaddr.sin_port = htons(_port);
        myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
        if (bind(_sockfd, (struct sockaddr*)&myaddr, sizeof(myaddr)) == -1)
        {
            std::cerr << "bind failed" << std::endl;
            exit(1);
        }
         std::cout << "bind success" << std::endl;
    }
    void Start()
    {
        char buff[SIZE] = { 0 };
        while (true)
        {
            struct sockaddr_in clientaddr;
            socklen_t addrlen = sizeof(clientaddr);
            int n = recvfrom(_sockfd, buff, sizeof(buff), 0, (struct sockaddr*)&clientaddr, &addrlen);
            std::cout << "client say: " << buff << std::endl;
            if (n > 0)
            {
                buff[n] = 0;
                std::string mess = _func(buff);
                std::cout << buff <<std::endl;
                sendto(_sockfd, mess.c_str(), mess.size(), 0, (struct sockaddr*)&clientaddr, addrlen);
            }
        }
    }

    ~UdpServer() 
    {
        close(_sockfd);
    }
private:
    int _sockfd;
    uint16_t _port;
    func_t _func;
};
